package com.li.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

/**
 * Created by Li on 2017/3/15.
 * 自适应ImageView
 * 根据drawable宽高自动按比例缩放
 */

public class AutoImageView extends ImageView
        implements ViewTreeObserver.OnGlobalLayoutListener {
    public AutoImageView(Context context) {
        this(context, null);
    }

    public AutoImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @SuppressWarnings("deprecation,unused")
    @Override
    public void onGlobalLayout() {
        Drawable drawable = getDrawable();
        if (drawable==null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }else {
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
            return;
        }
        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();
        int imgWidth = getWidth();
        int imgHeight = getHeight();

        //drawable宽度小于img宽度
        float scale = drawableWidth * 1.0f / drawableHeight;
        int newHeight = (int) (imgWidth/scale);
        ViewGroup.LayoutParams params=getLayoutParams();

        params.width=imgWidth;
        params.height=newHeight;
        setLayoutParams(params);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }else {
            getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }

    }
}
